package com.example.shardingsphere.controller;

import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.example.shardingsphere.entity.User;
import com.example.shardingsphere.service.UserService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * 用于测试 主从复制，读写分离
 */
@RequestMapping("/user")
@RestController
@ResponseBody
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/add/{name}")
    public Object add(@PathVariable String name) {
        User user = User.builder()
                .username(name)
                .email(name + "@example.com")
                .password(UUID.fastUUID().toString(true))
                .createTime(new Date())
                .build();
        boolean save = userService.save(user);
        return JSONUtil.toJsonStr(user);
    }

    @RequestMapping("/list")
    @Transactional //  事务的读写都会在主节点
    public Object list() {
        return JSONUtil.toJsonStr(userService.list());
    }

    @RequestMapping("/getById/{id}")
    public Object getById(@PathVariable Long id) {
        return JSONUtil.toJsonStr(userService.getById(id));
    }

    @PostMapping("/health")
    public Object health(@RequestBody Map<String, String> map) {
        System.out.println(map);
        return "health";
    }

}
